package com.jiaquyun.jcps.ui.main

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.TimeUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jiaquyun.jcps.R
import com.jiaquyun.jcps.base.ViewModeFragment
import com.jiaquyun.jcps.entity.OrderListEntity
import com.jiaquyun.jcps.mode.vm.MainViewModel
import com.lemlin.network.HttpServiceStatus
import com.yxing.ScanCodeActivity
import com.yxing.ScanCodeConfig
import com.yxing.def.ScanStyle
import kotlinx.android.synthetic.main.fragment_main.*


class MainPickupFragment : ViewModeFragment<MainViewModel>() {

    private val pickupAdapter =
        object : BaseQuickAdapter<OrderListEntity, BaseViewHolder>(R.layout.item_order_pickup) {
            init {
                addChildClickViewIds(R.id.tvPickupContactClient, R.id.tvPickupConfirmOrder)
            }

            override fun convert(holder: BaseViewHolder, item: OrderListEntity) {
                holder.setText(R.id.tvPickupOrderNo, "#${item.order_no}")
                    .setText(R.id.tvPickupAddressTake, item.start_address)
                    .setText(R.id.tvPickupAddressCollect, item.end_address)
                    .setText(
                        R.id.tvPickupRangeStart,
                        StringBuilder().append(item.distance).append("m")
                    )
                    .setText(
                        R.id.tvPickupRangeCollect,
                        StringBuilder().append(item.distance).append("m")
                    )
                    .setText(
                        R.id.tvPickupPrice,
                        StringBuilder().append("在线支付").append(item.order_amount).append("元")
                    )
                    .setText(
                        R.id.tvPickupTime,
                        StringBuilder().append("顾客下单时间")
                            .append(TimeUtils.millis2String((item.createtime * 1000), ("HH:mm")))
                    )
            }
        }

    companion object {
        fun newInstance(): MainPickupFragment {
            return MainPickupFragment()
        }
    }

    override fun viewModel(): MainViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.fragment_main

    private var orderListId: String? = null

    override fun initView() {
        rvMainBody.adapter = pickupAdapter

        pickupAdapter.setOnItemChildClickListener { adapter, view, position ->
            val itemData: OrderListEntity = pickupAdapter.getItem(position)
            if (view.id == R.id.tvPickupConfirmOrder) {
                orderListId = itemData.id.toString()
                ScanCodeConfig.create(requireActivity(), this)
                    //设置扫码页样式 ScanStyle.NONE：无  ScanStyle.QQ ：仿QQ样式   ScanStyle.WECHAT ：仿微信样式    ScanStyle.CUSTOMIZE ： 自定义样式
                    .setStyle(ScanStyle.WECHAT)
                    //扫码成功是否播放音效  true ： 播放   false ： 不播放
                    .setPlayAudio(false)
                    .buidler()
                    //跳转扫码页   扫码页可自定义样式
                    .start(ScanCodeActivity::class.java)
            } else if (view.id == R.id.tvPickupContactClient) {
                viewModel.callPhone(itemData.mobile)
            }
        }

        smartRefreshHeader.setColorSchemeResources(R.color.colorMain)

        smartRefreshLayout.setOnRefreshListener {
            viewModel.orderListTab()
            viewModel.orderListPickUp()
        }
    }

    override fun initData() {
        smartRefreshLayout.autoRefresh()
    }

    override fun initViewMode() {
        viewModel.orderPickupLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.statusCode == HttpServiceStatus.Status.FAILURE) {
                smartRefreshLayout.finishRefresh(false)
                toast(response.statusTip)
            }
            if (response.statusCode == HttpServiceStatus.Status.SUCCESS) {
                smartRefreshLayout.finishRefresh()
                response.httpData?.data?.let {
                    pickupAdapter.setList(it)
                }
            }
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && requestCode == ScanCodeConfig.QUESTCODE && data != null) {
            val extras: Bundle? = data.extras
            if (extras != null) {
                extras.getString(ScanCodeConfig.CODE_KEY)?.let { code ->
                    orderListId?.let { id ->
                        viewModel.orderWithdrawal(id, code)
                    }
                }
            }
        }
    }

}